#include "udp_client.hpp"
#include"err.hpp"
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<iostream>
#include<cstring>

static void usage(std::string proc)
{
    std::cout<<"Usage:\n\t"<<proc<<"serverip serverport\n"<<std::endl;
}
int main(int argc,char* argv[])
{
    if(argc!=3)
    {
        usage(argv[0]);
        exit(USAGE_ERR);
    }
    std::string serverip=argv[1];
    uint16_t serverport=atoi(argv[2]);
    int sock=socket(AF_INET,SOCK_DGRAM,0);
    if(sock<0)
    {
        std::cout<<"socket create erro"<<std::endl;
        exit(SOCKET_ERR);
    }
    //client端口号有os分配
    struct sockaddr_in server;
    memset(&server,0,sizeof(server));
    server.sin_family=AF_INET;
    server.sin_port=htons(serverport);
    server.sin_addr.s_addr=inet_addr(serverip.c_str());
    while (true)
    {
        //输入
        std::string message;
        std::cout<<"please enter# ";
        std::cin>>message;
        
        //发送给server

        sendto(sock,message.c_str(),message.size(),0,(struct sockaddr*)&server,sizeof(server));

        //接受
        char buffer[1024];
        struct sockaddr_in temp;
        socklen_t len=sizeof(temp);
        int n=recvfrom(sock,buffer,sizeof(buffer)-1,0,(struct sockaddr*)&temp,&len);
        if(n>0)
        {
            buffer[n]='\0';
            std::cout<<"server echo# "<<std::endl;
        }
    }
    
    return 0;
}